<template>
    <div>
        <div class="reuse-tab ad-rt fixed" :class="!collapsed? 'collapsednam_a':'collapsednam'"
             @click="showBox =false">
            <a-tabs :activeKey="activeKey" type="line" >
                <a-tab-pane v-for="item in navTabs" :key="item.key">
                    <div slot="tab">
                        <span @click="callback(item.key,item)" class="name"  @contextmenu.prevent="contextmenuShow($event,item)">{{ $i18(item.title,'菜单名称')}}</span>
                        <a-icon v-if="!['home-index','admin-index'].includes(item.key)" :class="['op op1']" @click="onDelete(item)" type="close"/>
                    </div>
                </a-tab-pane>
            </a-tabs>
            <div v-if="showBox">
                <div class="show-parent" :style="contextmenuStyle">
                    <ul>
                        <li @click="closeCurrent()"> {{i18n('navigationBar.currentTAB','关闭当前页签')}}</li>
                        <li @click="closeOther"> {{i18n('navigationBar.otherTAB','关闭其它页签')}}</li>
                        <li @click="closeLeft"> {{i18n('navigationBar.leftTAB','关闭左侧页签')}}</li>
                        <li @click="closeRight"> {{i18n('navigationBar.rightTAB','关闭右侧页签')}}</li>
                        <li @click="closeWhole"> {{i18n('navigationBar.allTAB','关闭全部页签')}}</li>
                    </ul>
                </div>
            </div>
        </div>

    </div>
</template>
<script>
import {mapState,mapMutations,mapGetters} from 'vuex'
import {initGlobalState} from "qiankun";
import miniFront from "../../miniFront/miniFront";
import {getParentPath} from "@/utils/routerUtil";
import compomentLang from '../../../locales/lang/impl/layouts/compomentLang';

import openMenus from "@/layouts/compoment/main/openMenus";
import {JsConstant} from "@lowcode/jpaas-common-lib";
import RxIcon from "@/components/rxComponent/rx-icon";
export default {
    name: 'navigation-bar',
    components: {RxIcon},
    mixins:[miniFront,openMenus],
    data() {
        return {
            mode: 'top',
            showBox: false,
            contextmenuStyle:{
                'left':0,
                'top':0
            },
            contextmenuActive:{},//tab右键菜单时选中的数据；
            customArr: ['customIcon', 'userCustomIcon','jpaasIcon'],
            targetKeyObj:{
                FUNS:'funs', //功能面板集（标签）
                FUNS_BLOCK:'funsBlock',//功能面板集（单页）
                FUN:'FUN'//功能面板
            },
            homeArr: {
                admin:{
                    key: 'admin-index',
                    title: this.getHomeArrTitle(),
                    collapsed: false,
                    showType:"URL"
                },
                user:{
                    key: 'home-index',
                    title: this.getHomeArrTitle(),
                    collapsed: false,
                    showType:"URL"
                }
            }
        }
    },

    computed: {
        ...mapGetters({'appKey' : 'appSetting/getAppKey','activeKey':'appSetting/getActiveKey'} ),
        ...mapState({
            menus: state => state.appSetting.menus,
            navigation: state => state.appSetting.navigation,
            appmenuId: state => state.appSetting.appmenuId,
            showType: state => state.appSetting.showType,
            openFrontData: state => state.appSetting.openFrontData,
            activeFront: state => state.appSetting.activeFront,
            collapsed: state => state.appSetting.collapsed,
            // 前端类型 (user,前台,admin 后台)
            frontType:(state) => state.appSetting.frontType,
        }),
        /**
         * 获取当前的TAB
         * @returns {*}
         */
        navTabs(){
            let tabs= this.navigation[this.frontType];
            return tabs;
        },


    },
    created() {
        if (!this.$bus.closeTab) {
            this.$bus.on("closeTab", (obj) => {
                if (obj.action === "current") {
                    this.closeCurrent();
                }
            });
            this.$bus.closeTab = true;
        }
    },
    mounted() {
        document.addEventListener('click',this.contextVisible)
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "compomentLang", key);
        },
        getHomeArrTitle(){
            let lang=compomentLang.compomentLang.navigationBar.homePage;
            return JSON.stringify(lang);
        },
        ...mapMutations('appSetting', ['setActiveKey', 'setNavigation',
            'setAppMenuId', 'setSelecteKeys', 'setOpenKeys','setOpenFront','setCollapsed',
            'setActiveFront','setAppKey'
        ]),
        // 删除
        onDelete(item) {
            this.contextmenuActive = item;
            this.closeCurrent()
        },

        handOpenPortal(item){//打开内置微前端
            if(this.activeFront && (this.activeFront.appId != item.appId || !this.activeFront.hasOwnProperty('appId'))){
                let _activeData = this.menus.find(front=>{return front.appId == item.appId })
                let _parent = this.$router.options.routes.find(parent=>{
                    return parent.id == item.appId ;
                })
                let parentMenuArr = getParentPath([_parent], item.id);
                let _path = parentMenuArr.reverse().map(obj=>{
                    return obj.path ;
                }).join('/')
                this.setOpenFront(true);
                this.$emit('adhibitionUser',_activeData);
                this.innnerFrontOpen(_activeData,_path,item);
                return ;
            }
            //配置左边菜单选择key
            this.setSelecteKeys([item.key]);
            //配置tab选中key
            this.setActiveKey(item.key);
            this.setFrontDatas(item);
        },
        setFrontDatas(data){
            //给微前端传入数据；
            let state = {data:data}
            const actions = initGlobalState({});
            actions.setGlobalState(state);
        },
        //选中
        callback(targetKey, pane) {
            let homeIndexKey=this.homeArr[this.frontType].key;
            if( ['2'].includes(pane.menuNavType) ){
                    //2 内置微前端，3自定义微前端
                this.handOpenPortal(pane);
                return ;
            }
            if(window.Vue2){
                window.Vue = window.Vue2;
                window.Vue2 = undefined;
            }
            //清除微前端选中；
            this.setActiveFront({})
            //设置是否打开微前端，这里全部给false,当进入微前端时，会在main.js中设置状态;
            this.setOpenFront(false);

            this.setActiveKey(targetKey)
            if(pane.showType){
                targetKey = this.targetKeyObj[pane.showType] ? this.targetKeyObj[pane.showType] : targetKey;
            }
            var pathParams = {name: targetKey}
            if(pane.id){
                pathParams.params = {menuId: pane.id};
            }
            if (pane.params) {
                if(pane.params.toString.call(pane.params).indexOf('Object') < 0 && pane.params.indexOf('{')>-1){
                    pathParams.params = JSON.parse(pane.params)
                }else{
                    pathParams.params=pane.params;
                }
            }
            if(pane.appType==='1'){
              pathParams.query={appId:pane.appId};
            }
            if(pathParams.params && pathParams.params.menuId){
                this.setAppMenuId(pathParams.params.menuId);
            }
            if(pane.path){
                pathParams.path=pane.path;
            }
            if(pane.query){
                pathParams.query=pane.query;
            }
            this.setSelecteKeys([targetKey]);
            if (this.showType && this.showType === 'window' && pane.showType === 'URL'){
                this.$router.push(pathParams);
            }else {
                let _objFun = {
                    "POP_WIN": {fn: 'openPopWin'},   //弹窗
                    "NEW_WIN": {fn: 'openNewWin'},        //新窗口
                    "FUNS": {fn: 'openFuns', parames: 'funs'},    //功能面板集（标签）
                    "FUNS_BLOCK": {fn: 'openFuns', parames: 'funsBlock'},   //功能面板集（单页）
                    "FUN": {fn: 'openFuns', parames: 'fun'}   //功能面板
                }
                let _fn = _objFun[pane.showType].fn;
                let _parames = _objFun[pane.showType].parames;
                this[_fn](pane, _parames);
            }

            if(pane.key === homeIndexKey){
                sessionStorage.removeItem(JsConstant.CUR_APP_ID);
                sessionStorage.removeItem(JsConstant.CUR_APP_KEY);
            }
            if(pane.id || pane.key === homeIndexKey){
                this.$emit('navClick', pane);
            }
            this.setCollapsed(false);
        },
        contextVisible(){
            this.contextmenuActive = {};
            this.showBox = false;
        },
        contextmenuShow(e,item){
            e.preventDefault()
            let { top , left } = e.target.getBoundingClientRect();
            let clientWidth =  document.body.clientWidth ;
            let obj = {
                top:(top + 40 ) + 'px',
                left:(left + 15) + 'px'
            }
            if((left + 15 + 92) > clientWidth){
                obj = {
                    top:(top + 40 ) + 'px',
                    left:'auto',
                    right:'10px'
                }
            }
            this.contextmenuActive = item ;
            this.contextmenuStyle = obj ;
            this.showBox = true;
        },
        // 关闭当前标签
        closeCurrent() {
            let activeKey = this.contextmenuActive.key ;
            let homeIndexKey=this.homeArr[this.frontType].key;
            if(activeKey==homeIndexKey){
                return;
            }

            for (let i = 0; i <= this.navTabs.length; i++) {
                if (this.navTabs[i].key == activeKey) {
                    let nav = this.navTabs[i - 1];
                    this.callback(nav.key,nav);
                    this.navTabs.splice(i, 1);
                    break ;
                }
            }

        },
        // 关闭全部
        closeWhole() {
            let homeObj=structuredClone(this.homeArr[this.frontType]);
            this.navigation[this.frontType]=[homeObj];

            this.callback(homeObj.key,homeObj);
        },
        //关闭其他
        closeOther() {
            let activeKey = this.contextmenuActive.key ;
            let tab = this.navTabs.find(item=>{ return item.key == activeKey})
            let activeIndex = this.navTabs.findIndex(item=>{ return item.key == activeKey});
            let homeObj=structuredClone(this.homeArr[this.frontType]);
            //增加首页
            let list = [homeObj];
            //增加选中
            if(activeIndex!==0){
                list.push(tab)
            }
            this.navigation[this.frontType]=list;

            this.callback(tab.key,tab)
        },
        closeRight(){//关闭右边
            let activeKey = this.contextmenuActive.key ;
            let activeIndex = this.navTabs.findIndex(item=>{ return item.key == activeKey});
            let actives = this.navTabs.find(item=>{ return item.key == activeKey});
            let nav = this.navTabs.slice(0,activeIndex+1);
            this.navigation[this.frontType]=nav;

            this.callback(actives.key,actives)
        },
        closeLeft(){//关闭左边
            let activeKey = this.contextmenuActive.key ;
            let activeIndex = this.navTabs.findIndex(item=>{ return item.key == activeKey});
            if(activeIndex!==0){
                let navArr = this.navTabs.slice(activeIndex);
                let homeObj=structuredClone(this.homeArr[this.frontType]);
                navArr=[homeObj,...navArr];
                this.navigation[this.frontType]=navArr;

                let actives = this.navTabs.find(item=>{ return item.key == activeKey});
                this.callback(actives.key,actives)
            }
        }
    }
}
</script>

<style lang="less">
.lanlist_home:hover{
    cursor: pointer;
}
.reuse-tab .lanlist {
    margin-left: 20px;
    margin-top: 7px;
}
.show-parent {
    position: fixed!important;
    background-color: #ffffff;
    box-shadow: 0 0 2px #8c939d;
    border-radius: 5px;
    z-index: 999;
    font-size: 12px;
}
.show-parent ul{
    margin-bottom: 0;
}

.show-parent ul li {
    padding:4px 10px;
}

.show-parent ul li:hover {
    background-color: #e7f4ff;
    cursor: pointer;
}

@reuse-tab-prefix: ~'.reuse-tab';
@reuse-tab-height: 52px;
@reuse-tab-bg: #fff;
@reuse-tab-padding: 8px;
@reuse-tab-border-color: #d9d9d9;

@{reuse-tab-prefix} {
    display: block;
    background-color: @reuse-tab-bg;
    padding: @reuse-tab-padding;
    border-bottom: 1px solid @reuse-tab-border-color;
    outline: none;
    user-select: none;

    .ant-tabs-bar {
        margin-bottom: 0;
        border-bottom: none;
    }

    .ant-tabs-nav .ant-tabs-tab {
        padding: 0;
        margin: 0 10px 0 0;

        .name {
            display: inline-block;
            padding: 13px 15px;
        }

        .op {
            display: none;
            position: absolute;
            top: 18px;
            right: 2px;
            margin: 0;
            font-size: 12px;
            &:hover {
                color: red;
            }
        }

        &:hover {
            .op1 {
                display: block;
            }
        }
    }
}

.artup {
    &:hover {
        .op {
            display: block;
        }
    }
}

@{reuse-tab-prefix}__cm {
    .ant-menu {
        border: 1px solid #e9e9e9;
    }
}

.ad-rt {
    display: block;
    background-color: #fff;
    padding: 0px 3px;
    margin: 0 -24px 0 -24px;
    border-bottom: 1px solid #d9d9d9;
    outline: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    border-top: 1px solid #d9d9d9;
}

.ad-rt.fixed {
    margin: 0;
    z-index: 9;
    height: 48px !important;
}

/*.collapsednam_a {
    left: 200px;
}

.collapsednam {
    left: 80px;
}*/

.aside-collapsed {
    .ad-rt.fixed {
        position: fixed;
        top: 64px;
        left: 64px;
        right: 0;
        margin: 0;
        z-index: 10;
    }
}
</style>
